import Vue from 'vue'
import VueRouter from 'vue-router'
// import Layout from '@/views/Layout'
// import Login from '@/views/Login'
// import My from '@/views/My'
// import Home from '@/views/Home'
// import Cart from '@/views/Cart'
// import Category from '@/views/Category'
// import GoodsDetail from '@/views/GoodsDetail'
// import Ordergoods from '@/views/Ordergoods'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

const Layout = () => import('@/views/Layout')
const Login = () => import('@/views/Login')
const My = () => import('@/views/My')
const Home = () => import('@/views/Home')
const Cart = () => import('@/views/Cart')
const Category = () => import('@/views/Category')
const GoodsDetail = () => import('@/views/GoodsDetail')
const Ordergoods = () => import('@/views/Ordergoods')

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
// 修改原型对象中的push方法
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: '/home',
    meta: { title: '主页' },
    children: [
      {
        path: 'my',
        component: My,
        name: 'My',
        meta: { isAuth: true, title: '我的' }
      },
      { path: 'home', component: Home, name: 'Home', meta: { title: '主页' } },
      {
        path: 'cart',
        component: Cart,
        name: 'Cart',
        meta: { title: '购物车' }
      },
      {
        path: 'category',
        component: Category,
        name: 'Category',
        meta: { title: '分类' }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登入' }
  },
  {
    path: '/detail/:proid',
    component: GoodsDetail,
    meta: { title: '商品详情' }
  },
  {
    path: '/ordergoods',
    name: 'Ordergoods',
    component: Ordergoods,
    meta: { title: '订单', isAuth: true }
  }
  // {
  //   path: '/about',
  //   // route level code-splitting
  //   name: 'about',
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
]

const router = new VueRouter({
  mode: 'hash',
  // base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  nProgress.start()
  nProgress.configure({ showSpinner: false })
  if (!to.meta.isAuth) return next()
  if (!store.state.user.token) {
    next('/login')
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  nProgress.done()
  document.title = to.meta.title
})

export default router
